﻿using shop.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace shop.Bll.trade
{
    public class TradeBll
    {

 
        /// <summary> 查询订单 </summary>
        public async Task<TradeResult> Query(DateTime begin, DateTime end, int page_size =40, int page_no =0,
            string shop_no ="", string warehouse_no=null)
        {
            // https://open.wangdian.cn/qyb/open/apidoc/doc?path=trade_query.php
            // 本接口不返回淘系及系统供销平台订单数据，

            var res = await new WdtApi()
                .UseUrl("trade_query")
                .AddParam("start_time", begin.ToString("yyyy-MM-dd HH:mm:ss"))
                .AddParam("end_time", end.ToString("yyyy-MM-dd HH:mm:ss"))
                .AddParamIfNotEmpty(nameof(warehouse_no), warehouse_no)
                .AddParamIfNotEmpty(nameof(shop_no), shop_no)
                .AddParam("page_size", page_size.ToString())
                .AddParam("page_no", page_no.ToString())
                .Post<TradeResult>();

            //if (res == null || res.trades == null )
            //{
            //    return null;
            //}

            return res;
        }

        //public async Task<List<tradeData>> testQuery()
        //{
        //    var list = await DB.FSql.Select<tradeData>()
        //        .Take(1000)
        //        .ToListAsync();

        //    return list;
        //}


        /// <summary> 同步订单数据到本地服务器 </summary>
        public async Task<bool> SyncTradeData(DateTime begin , DateTime end)
        {
            //https://open.wangdian.cn/qyb/open/apidoc/doc?path=trade_query.php
            //start_time和end_time最大跨度为60分钟，开始时间和结束时间取值范围为闭区间取值，例如2018-11-01 00:00:00至2018-11-01 00:59:59

            int size = 100;

            string err = null;

            if(end > DateTime.Now.AddMinutes(-1))
            {
                end = DateTime.Now.AddMinutes(-1);
            }

            while (true)
            {
                if (begin >= end)
                {
                    break;
                }
                var next = begin.AddHours(1);

                int page = 0;
                int total = 0;
                //int count = 0;
                var list = new List<tradeData>();

                while (true)
                {
                    var res = await Query(begin, next, size, page);

                    if (res == null || res.code !=0)
                    {
                        err = res.message;
                        throw new Exception(err);
                        //return false;
                    }

                    if (page==0)
                    {
                        total = res.total_count;
                    }

                    if (res.trades == null || res.trades.Count() ==0)
                    {
                        break;
                    }



                    list.AddRange(res.trades);

                    if (res.trades.Count() < size)
                    {
                        break;  //结束分页查询
                    }

                    page++;
                }

                //存储到数据库
                await Save(list);

                begin = begin.AddHours(1);
            }

            //处理重复的

            return true;

        }




        private async Task<int> Save(IEnumerable<tradeData> list)
        {
            //var c= await DB.FSql.InsertOrUpdate<tradeData>()
            //    .SetSource(list)
            //    .ExecuteAffrowsAsync();
            var c = await DB.FSql.Insert<tradeData>(list)
    .ExecuteAffrowsAsync();

            return c;
        }


    }
}
